//
//  StockVKLineVolumeView.m
//  K线图自治
//
//  Created by LK-IOS on 2017/12/20.
//  Copyright © 2017年 LK-IOS. All rights reserved.
//

#import "StockVKLineVolumeView.h"
#import "UIView+StockViewExtension.h"
#import "UIColor+StockColorEntension.h"
#import "StockConst.h"
#import "StockTimeVolumePositionModel.h"
#import "StockCalculationTool.h"
#import "StockLinePointModel.h"

#import "UIBezierPath+StockDraw.h"


#define VolumeViewScale 0.2


@interface StockVKLineVolumeView()





/**
 绘制在当前屏幕上的数据数组
 */
@property (nonatomic , strong) NSMutableArray *disPlayModelArray;

/**
 绘制在当前屏幕上的数据位置数组
 */
@property (nonatomic , strong) NSMutableArray *disPlayPositionArray;



@property (nonatomic,strong) CAShapeLayer   *VolumeLayer;

//MA5
@property (nonatomic,strong) CAShapeLayer *ma5LineLayer;
//MA10
@property (nonatomic,strong) CAShapeLayer *ma10LineLayer;



/**
 MA位置数组
 */
@property (nonatomic , strong) NSMutableArray *maPostionArray;


/**
 MA线数组
 */
@property (nonatomic , strong) NSMutableArray *maLines;


@end

@implementation StockVKLineVolumeView


-(NSMutableArray *)disPlayModelArray
{
    if (_disPlayModelArray == nil) {
        _disPlayModelArray = [NSMutableArray array];
    }
    return _disPlayModelArray;
}

-(NSMutableArray *)disPlayPositionArray
{
    if (_disPlayPositionArray == nil) {
        _disPlayPositionArray = [NSMutableArray array];
    }
    return _disPlayPositionArray;
}

-(NSMutableArray *)maPostionArray
{
    if (_maPostionArray == nil) {
        _maPostionArray = [NSMutableArray array];
    }
    return _maPostionArray;
}

-(NSMutableArray *)maLines
{
    if (_maLines == nil) {
        _maLines = [NSMutableArray array];
    }
    return _maLines;
}

- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
    
    
}


-(void)stockFill
{
    [self initConfig];//初始化属性
    
    [self removeSubLayer];//移除原有的图层
    
    [self removeAllObjectFromArray];//清空所有数据数组
    
    [self upDateDisPlayModelArray];//更新要绘制的数据源
    
    
    [self layoutIfNeeded];
    
    [self calcuteMaxAndMinValue];//计算最大值和最小值及缩放比例
    
    [self calModelPositions];//计算每一个数据的位置
    
    [self addVolumeLayer];//添加成交量图层
    
    [self startDrawVolumeLayer];//开始绘制
    
    
    
    [self startDrawMaLayer];//绘制MA线
}

/**
 初始化属性
 */
-(void)initConfig
{
    self.lineWidth = 1.0f;
}

/**
 移除成交量图层
 */
-(void)removeSubLayer
{
    for (NSInteger i = 0 ; i < self.VolumeLayer.sublayers.count; i++)
    {
        CAShapeLayer *layer = (CAShapeLayer*)self.VolumeLayer.sublayers[i];
        [layer removeFromSuperlayer];
        layer = nil;
    }
    [self.VolumeLayer removeFromSuperlayer];
    self.VolumeLayer = nil;

}

/**
 清空所有数据数组
 */
- (void)removeAllObjectFromArray
{
    if (self.disPlayModelArray.count>0)
    {
        [self.disPlayModelArray removeAllObjects];
        [self.disPlayPositionArray removeAllObjects];
    }
}


/**
 更新要绘制的数据源
 */
-(void)upDateDisPlayModelArray
{    
    if (_startIndex + _displayCount > _dataArray.count)
    {
        [self.disPlayModelArray addObjectsFromArray:[self.dataArray subarrayWithRange:NSMakeRange(_startIndex,_displayCount-1)]];
    }
    
    else
    {
        [self.disPlayModelArray addObjectsFromArray:[self.dataArray subarrayWithRange:NSMakeRange(_startIndex,_displayCount)]];
    }
}

/**
 计算最大值和最小值
 */
-(void)calcuteMaxAndMinValue
{
    
    //    CGFloat minValue =  [[[self.disPlayModelArray valueForKeyPath:@"Volume"] valueForKeyPath:@"@min.floatValue"] floatValue];
    //    CGFloat maxValue =  [[[self.disPlayModelArray valueForKeyPath:@"Volume"] valueForKeyPath:@"@max.floatValue"] floatValue];
    
    CGFloat maxValue =  [[[self.disPlayModelArray valueForKeyPath:@"Volume"] valueForKeyPath:@"@max.floatValue"] floatValue];
    self.maxDisplayVolume = maxValue;
    
    CGFloat minY = 1.0;
    CGFloat maxY = self.height - 1.0;

    self.maxY = maxY;//线的最大高度
    self.minY = minY;//线的最大高度距离视图顶部的距离

    //Y值缩放比例
    self.scaleY = (maxY - minY) / maxValue;
    
}


/**
 计算每一个数据的位置
 */
-(void)calModelPositions
{
    for (int i = 0; i < self.disPlayModelArray.count; i++) {
        StockKLineModel *model = self.disPlayModelArray[i];

        //定位每个数据的X点
        CGFloat xPosition = self.leftPostion + i * (self.candleWidth + self.candleSpace);
        //定位每个数据的Y点
        CGFloat yPosition = ABS(self.maxY - [model.Volume floatValue] * self.scaleY);
        //整个方块区域的开始点
        CGPoint startPoint = CGPointMake(xPosition, yPosition);
        //整个方块的结束点
        CGPoint endPoint = CGPointMake(xPosition, 0);
        
        //根据每条数据获取的开始点结束点，以及时间，创建每一个成交量模型
        StockTimeVolumePositionModel *positionModel = [StockTimeVolumePositionModel modelWithStartPoint:startPoint endPoint:endPoint dayDesc:model.date];
        [self.disPlayPositionArray addObject:positionModel];
    }
}


/**
 添加成交量图层
 */
-(void)addVolumeLayer
{
    if (!self.VolumeLayer.sublayers.count)
    {
        [self.layer addSublayer:self.VolumeLayer];
    }
}

/**
 开始绘制图层
 */
-(void)startDrawVolumeLayer
{

    __weak typeof(self) this = self;
    [self.disPlayPositionArray enumerateObjectsUsingBlock:^(StockTimeVolumePositionModel* obj, NSUInteger idx, BOOL * _Nonnull stop) {
        StockKLineModel *kDataModel = this.disPlayModelArray[idx];

        CAShapeLayer *layer = [this drawVolumeLayer:obj KDataModel:kDataModel];
        [this.VolumeLayer addSublayer:layer];
        
        
        
    }];
    
}


/**
 绘制
 */
- (CAShapeLayer*)drawVolumeLayer:(StockTimeVolumePositionModel*)positionModel KDataModel:(StockKLineModel*)kDataModel
{
    
    
    CGRect rect = CGRectZero;
    rect = CGRectMake(positionModel.StartPoint.x , self.maxY , self.candleWidth , positionModel.StartPoint.y - self.maxY);
    
    UIBezierPath *path = [UIBezierPath bezierPathWithRect:rect];
    CAShapeLayer *subLayer = [CAShapeLayer layer];
    subLayer.path = path.CGPath;
    if ([kDataModel.priceUpDown floatValue] >=0) {
        subLayer.strokeColor = [UIColor Stock_PriceUpColor].CGColor;
        subLayer.fillColor = [UIColor Stock_PriceUpColor].CGColor;
    }else{
        subLayer.strokeColor = [UIColor Stock_PriceDownColor].CGColor;
        subLayer.fillColor = [UIColor Stock_PriceDownColor].CGColor;
    }
    return subLayer;
}

/**
 绘制MA线
 */
-(void)startDrawMaLayer
{
    
    [self addMaLayer];
    [self calMaPositon];
    
    [self drawMaLineLayer];
}



/**
 计算MA线
 */
-(void)calMaPositon
{
    [self.maPostionArray removeAllObjects];
    [self.maLines removeAllObjects];
    
    CGFloat MAMaxY = CGFLOAT_MIN;
    CGFloat MAMinY = CGFLOAT_MAX;
    NSInteger idx = 0;
    //遍历当前范围内显示的K线模型数组
    for (NSInteger i = idx; i < self.disPlayModelArray
         .count; i++)
    {
        StockKLineModel * entity = [self.disPlayModelArray objectAtIndex:i];
        MAMinY = MAMinY < [entity.Low floatValue] ? MAMinY : [entity.Low floatValue];
        MAMaxY = MAMaxY > [entity.High floatValue] ? MAMaxY : [entity.High floatValue];
        
        if (self.maxY - self.minY < 0.5)
        {
            self.maxY += 0.5;
            self.minY -= 0.5;
        }
    }
    //Y值缩放比例
    CGFloat MAscaleY =(self.height - self.topMargin - self.bottomMargin) / (MAMaxY - MAMinY);

    
    
    
    //颠倒元素
    NSMutableArray *array = (NSMutableArray *)[[self.disPlayModelArray reverseObjectEnumerator] allObjects];
    [self.maLines addObject:computeMAData(array,5)];
    [self.maLines addObject:computeMAData(array,10)];
    
    
    for (NSInteger i = 0;i<self.maLines.count;i++)
    {
        StockLineData *lineData = [self.maLines objectAtIndex:i];
        NSMutableArray *array = [NSMutableArray array];
        for (NSInteger j = 0;j <lineData.data.count; j++)
        {
            StockKLineUntil *until = lineData.data[j];
            
            CGFloat xPosition = self.leftPostion + ((self.candleWidth  + self.candleSpace) * j) + self.candleWidth/2;
            CGFloat yPosition = (MAMaxY - until.value) *MAscaleY + self.topMargin;
            StockLinePointModel *model = [StockLinePointModel  initPositon:xPosition yPosition:yPosition color:lineData.color];
            [array addObject:model];
            
            
        }
        [self.maPostionArray addObject:array];
    }

}

/**
 添加MA线图层
 */
-(void)addMaLayer
{
    //ma5
    if (self.ma5LineLayer)
    {
        [self.ma5LineLayer removeFromSuperlayer];
    }
    
    if (!self.ma5LineLayer)
    {
        self.ma5LineLayer = [CAShapeLayer layer];
        self.ma5LineLayer.lineWidth = self.lineWidth;
        self.ma5LineLayer.lineCap = kCALineCapRound;
        self.ma5LineLayer.lineJoin = kCALineJoinRound;
    }
    [self.layer addSublayer:self.ma5LineLayer];
    
    //ma10
    if (self.ma10LineLayer)
    {
        [self.ma10LineLayer removeFromSuperlayer];
    }
    
    if (!self.ma10LineLayer)
    {
        self.ma10LineLayer = [CAShapeLayer layer];
        self.ma10LineLayer.lineWidth = self.lineWidth;
        self.ma10LineLayer.lineCap = kCALineCapRound;
        self.ma10LineLayer.lineJoin = kCALineJoinRound;
    }
    [self.layer addSublayer:self.ma10LineLayer];
}

/**
 绘制MA线
 */
-(void)drawMaLineLayer
{
    NSMutableArray *pathsArray = [UIBezierPath drawLines:self.maPostionArray];
    
    StockLinePointModel *ma5Model = self.maPostionArray[0][0];
    StockLinePointModel *ma10Model = self.maPostionArray[1][0];
    
    UIBezierPath *ma5Path = pathsArray[0];
    self.ma5LineLayer.path = ma5Path.CGPath;
    self.ma5LineLayer.strokeColor = ma5Model.lineColor.CGColor;
    self.ma5LineLayer.fillColor = [[UIColor clearColor] CGColor];
    self.ma5LineLayer.contentsScale = [UIScreen mainScreen].scale;
    
    UIBezierPath *ma10Path = pathsArray[1];
    self.ma10LineLayer.path = ma10Path.CGPath;
    self.ma10LineLayer.strokeColor = ma10Model.lineColor.CGColor;
    self.ma10LineLayer.fillColor = [[UIColor clearColor] CGColor];
    self.ma10LineLayer.contentsScale = [UIScreen mainScreen].scale;
}


/**
 创建成交量图层
 */
- (CAShapeLayer*)VolumeLayer
{
    if (!_VolumeLayer)
    {
        _VolumeLayer = [CAShapeLayer layer];
        _VolumeLayer.lineWidth = _lineWidth;
        _VolumeLayer.strokeColor = [UIColor clearColor].CGColor;
        _VolumeLayer.fillColor = [UIColor clearColor].CGColor;
    }
    return _VolumeLayer;
}




@end
